package tgc.edu.ljc.bookmanage.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.ljc.bookmanage.custom.EasyuiResult;
import tgc.edu.ljc.bookmanage.entity.TbDept;
import tgc.edu.ljc.bookmanage.security.SysDept;
import tgc.edu.ljc.bookmanage.service.TbDeptService;
import tgc.edu.ljc.bookmanage.web.form.TbDeptForm;

@Controller
@RequestMapping(value="/dept")
public class TbDeptController {
	@Autowired
	private TbDeptService service;
	
	@RequestMapping(value="/manage")
	public void manage() {
		
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(Integer id) {
		List<HashMap<String, Object>> list=new ArrayList<>();
		if(id==null) {
			list=service.findTreeByParentIsNull();
		}else {
			list=service.findTreeByParentId(id);
		}
		return list;
	}
	
	@RequestMapping(value="/edit")
	public void edit(Integer parent,Integer id,ModelMap map) {
		TbDept model=new TbDept();
		if(id!=null) {
			model=service.findById(id);
		}
		if(parent!=null) {
			model.setParent(new SysDept(parent));
		}
		map.put("model", model);
	}
	
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(TbDeptForm form) {
		try {
			TbDept model=new TbDept();
			Integer id = form.getId();
			if(id!=null) {
				model=service.findById(id);
			}
			if(form.getParentId()==null) {
				model.setParent(null);
			}else {
				SysDept parent=service.findById(form.getParentId());
				model.setParent(parent);
			}
			BeanUtils.copyProperties(form, model,"id","parent");
			service.save(model);
			return new EasyuiResult("数据保存成功");
		} catch (Exception e) {
			return new EasyuiResult(false,"数据保存失败");
		}
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		try {
			service.deleteById(id);
			return new EasyuiResult("数据删除成功");
		} catch (Exception e) {
			return new EasyuiResult(false, "数据删除失败");
		}
	}
	
	@RequestMapping(value="/combotree")
	@ResponseBody
	public Object combotree(Integer id,Integer nodeId) {
		List<HashMap<String, Object>> result=service.combotree(id,nodeId);
		return result;
	}
}
